//logs.js
const util = require('../../utils/util.js');
const app = getApp();
import Api from '../../utils/api';
Page({
  data: {
    logs: [],
    userInfo: "",
    canIUse: true,
    buttomB: true,
    advertisement: '', //广告数据
  },
  onLoad: function() {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))
      })
    })
  },
  //获取用户信息
  userInfo: function(e) {
    let _this = this;
    console.log(e, "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
    if (!_this.data.buttomB) {
      return;
    }
    if (e.detail.errMsg == 'getUserInfo:ok') {
      _this.setData({
        userInfo: e.detail.userInfo,
        buttomB: false,
      })

      wx.setStorageSync("userInfo", e.detail.userInfo);
      _this.userLogin();
      console.log('允许授权', e.detail.userInfo);
    } else {
      console.log('拒绝授权');
      //设置未登录标记
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.setData({
        loginBackFlag: true
      });
      wx.navigateBack({
        delta: 2
      })
    }
  },

  onUnload: function() {
    console.log('log页面====onUnload')
  },
  /**
   * 用户登陆
   * 
   */
  userLogin: function () {
    let _this = this;
    wx.showLoading({
      title: '正在跳转...',
    })
    wx.login({
      success: res => {
        console.log(res);
        wx.setStorageSync('code', res.code);
        Api.login(res.code).then(res => {
          console.log(res)
          wx.setStorageSync("third_Session", res.data);
          Api.saveUserInfo(_this.data.userInfo).then(res => {
            console.log('保存用户信息', res);
            _this.setData({
              buttomB: true,
            })
            //设置前页登录标记
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              loginFlag: true
            });
            app.globalData.loginFlag=true;
           
            wx.navigateBack({
              delta: 1,
              success:function(res){
                console.log(res)
                wx.hideLoading();

              }
            })
         
          })
        })
      }
    })
  }
})